package demo.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import org.apache.commons.lang.StringUtils;

import java.io.Serializable;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;

public class JsonUtils implements Serializable {

    private static final long serialVersionUID = -4067763405310397425L;

    //导致fastjson反解析失败，需要删除的非法字符集
    private static final char[] illegalRemovedChars = {
            '\u001A'//play的播放数据显示的^Z导致泛解析失败，是个end-of-file字符
    };

    public static <T> String toJson(T o) {
        String s = "";
        s = JSON.toJSONString(o, SerializerFeature.DisableCircularReferenceDetect);
        return s;
    }

    /**
     * 转成json字节数组，相比 JSON.toJSONString().getBytes() 性能稍高
     *
     * @param o
     * @return
     */
    public static byte[] toJSONBytes(Object o) {
        return JSON.toJSONBytes(o, SerializerFeature.DisableCircularReferenceDetect);
    }

    public static <T> List<T> fromJsonArray(String json, Class<T> clazz) {
        List<T> list = new ArrayList<T>();
        list = JSON.parseArray(json, clazz);
        return list;
    }

    public static <T> T fromJson(String json, Class<T> clazz) {
        for (int i = 0; i < illegalRemovedChars.length; i++) {
            json = StringUtils.remove(json, illegalRemovedChars[i]);
        }
        return JSON.parseObject(json, clazz);
    }
}
